from gradio_client import Client, handle_file
import sys
import io
import logging

# 强制所有输出使用UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,
    encoding='utf-8',
    errors='replace'  # 自动替换无法编码的字符
)
sys.stderr = io.TextIOWrapper(sys.stderr.buffer,
    encoding='utf-8',
    errors='replace'
)

# 抑制第三方库的冗余输出
logging.basicConfig(level=logging.WARNING)

if __name__ == "__main__":
    try:
        # 显式编码输出（可选增强）
        args_str = " ".join(sys.argv).encode('utf-8', errors='replace').decode('utf-8')
        print(f"Python脚本接收到参数: {args_str}")

        if len(sys.argv) < 3:
            sys.stderr.write("错误：参数不足\n")
            sys.exit(1)

        # 创建客户端时禁用输出
        question = sys.argv[1]
        url = str(sys.argv[2])
        print(question)
        print(url)
        client = Client("http://127.0.0.1:6006/", verbose=False)
        result = client.predict(
            image=handle_file("https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"),
            question=question,
            seed=42,
            top_p=0.95,
            temperature=0.1,
            api_name="/multimodal_understanding"
        )
        print(result)
        sys.exit(0)
    except Exception as e:
        sys.stderr.write(f"致命错误: {str(e)}\n")
        sys.exit(2)

